<template>
  <div class="page">
    <h2>专用处方开具</h2>

    <div class="controls">
      <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;width:100%">
        <el-input v-model="searchPatient" placeholder="搜索患者：姓名/卡号" clearable style="width:320px" @clear="onClearSearch" />

        <el-button type="primary" @click="openNewPrescription">新建处方</el-button>
        <el-button @click="loadTemplate">加载模板</el-button>
        <el-button @click="saveTemplate">保存为模板</el-button>
        <el-button @click="exportPrescription">导出处方（CSV）</el-button>

        <div style="flex:1"></div>
        <div class="muted">提示：页面为前端静态演示，处方仅保存在内存（模拟后端）。</div>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="9">
        <el-card>
          <div class="card-title">患者信息</div>
          <el-form :model="patient" label-width="90px">
            <el-form-item label="姓名"><el-input v-model="patient.name" /></el-form-item>
            <el-form-item label="性别">
              <el-select v-model="patient.gender" placeholder="请选择" style="width:120px">
                <el-option label="男" value="M" />
                <el-option label="女" value="F" />
                <el-option label="未知" value="U" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄"><el-input-number v-model="patient.age" :min="0" /></el-form-item>
            <el-form-item label="就诊号"><el-input v-model="patient.visitNo" /></el-form-item>
            <el-form-item label="科室"><el-input v-model="patient.department" /></el-form-item>
            <el-form-item label="诊断/主诉"><el-input v-model="patient.diagnosis" /></el-form-item>
          </el-form>
        </el-card>

        <div style="margin-top:12px">
          <el-card>
            <div class="card-title">处方信息</div>
            <el-form :model="prescription" label-width="100px">
              <el-form-item label="处方类型">
                <el-select v-model="prescription.type" style="width:180px">
                  <el-option label="门诊处方" value="outpatient" />
                  <el-option label="住院处方" value="inpatient" />
                  <el-option label="专用处方" value="special" />
                </el-select>
              </el-form-item>
              <el-form-item label="医师姓名"><el-input v-model="prescription.doctor" /></el-form-item>
              <el-form-item label="开具日期"><el-date-picker v-model="prescription.date" type="date" placeholder="选择日期" style="width:160px" /></el-form-item>
              <el-form-item label="备注"><el-input v-model="prescription.note" /></el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-col>

      <el-col :span="15">
        <el-card>
          <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
            <div class="card-title">处方药品清单</div>
            <div>
              <el-input v-model="drugSearch" placeholder="按药品名或编码搜索添加" size="small" style="width:220px;margin-right:8px" />
              <el-button size="small" type="success" @click="addDrugFromSearch">添加</el-button>
            </div>
          </div>

          <el-table :data="prescription.items" stripe border style="width:100%">
            <el-table-column prop="code" label="编码" width="120" />
            <el-table-column prop="name" label="药品名称" />
            <el-table-column label="剂量/频次" width="200">
              <template #default="{ row }">
                <el-input v-model="row.dosage" size="small" placeholder="例如：0.5g" style="width:100px;margin-right:6px" />
                <el-select v-model="row.frequency" size="small" placeholder="频次" style="width:86px">
                  <el-option label="qd(每日一次)" value="qd" />
                  <el-option label="bid(每日两次)" value="bid" />
                  <el-option label="tid(每日三次)" value="tid" />
                  <el-option label="qid(每日四次)" value="qid" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="route" label="途径" width="120">
              <template #default="{ row }"><el-select v-model="row.route" size="small" placeholder="口服" style="width:100%"><el-option label="口服" value="po" /><el-option label="注射" value="iv" /><el-option label="外用" value="topical" /></el-select></template>
            </el-table-column>
            <el-table-column prop="duration" label="疗程(天)" width="110">
              <template #default="{ row }"><el-input-number v-model="row.duration" :min="1" size="small" style="width:100%" /></template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="{ row }"><el-input-number v-model="row.quantity" :min="0" size="small" style="width:100%" /></template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template #default="{ row }">¥{{ (row.price||0).toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="小计" width="100">
              <template #default="{ row }">¥{{ ((row.price||0)*(row.quantity||0)).toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="removeItem(row.id)">删除</el-button>
                <el-button size="small" style="margin-left:8px" @click="duplicateItem(row.id)">复制</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div style="display:flex;align-items:center;justify-content:space-between;margin-top:10px">
            <div>
              <el-button type="primary" @click="validateAndSave">保存处方</el-button>
              <el-button @click="printPreview" style="margin-left:8px">打印预览</el-button>
            </div>
            <div class="muted">合计：¥{{ totalAmount.toFixed(2) }} &nbsp; | &nbsp; 药品数：{{ prescription.items.length }}</div>
          </div>

        </el-card>
      </el-col>
    </el-row>

    <!-- 打印预览模态 -->
    <el-dialog title="打印预览" v-model="showPreview" width="720px">
      <div style="font-size:14px">
        <h3>处方</h3>
        <div>患者：{{ patient.name }} | 性别：{{ patient.gender }} | 年龄：{{ patient.age }}</div>
        <div>医生：{{ prescription.doctor }} | 开方日期：{{ prescription.date }}</div>
        <table style="width:100%;margin-top:8px;border-collapse:collapse">
          <thead>
            <tr style="text-align:left;border-bottom:1px solid #ddd"><th>编码</th><th>名称</th><th>剂量/频次</th><th>途径</th><th>疗程</th><th>数量</th><th>备注</th></tr>
          </thead>
          <tbody>
            <tr v-for="it in prescription.items" :key="it.id" style="border-bottom:1px solid #f0f0f0">
              <td>{{ it.code }}</td><td>{{ it.name }}</td><td>{{ it.dosage }} / {{ it.frequency }}</td><td>{{ routeLabel(it.route) }}</td><td>{{ it.duration }}</td><td>{{ it.quantity }}</td><td>{{ it.note }}</td>
            </tr>
          </tbody>
        </table>
        <div style="margin-top:10px">总计：¥{{ totalAmount.toFixed(2) }}</div>
      </div>
      <template #footer>
        <el-button @click="showPreview=false">关闭</el-button>
        <el-button type="primary" @click="doPrint">打印</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 假数据药品库，参考 DrugCatalog 风格
const DRUG_LIBRARY = [
  {id:1,code:'D0001',name:'阿莫西林胶囊',price:12.5},
  {id:2,code:'D0002',name:'头孢克肟片',price:8.0},
  {id:3,code:'D0101',name:'维生素C片',price:5.2},
  {id:4,code:'D0003',name:'布洛芬片',price:6.5},
  {id:8,code:'D0007',name:'消毒棉片',price:4.5},
  {id:9,code:'D0008',name:'胰岛素注射液',price:120.0},
];

const searchPatient = ref('');
const drugSearch = ref('');

const patient = reactive({ name:'张三', gender:'M', age:34, visitNo:'OP123456', department:'精神科', diagnosis:'抑郁症' });

const prescription = reactive({
  id: 1,
  type: 'special',
  doctor: '李医生',
  date: new Date().toLocaleDateString(),
  note: '',
  items: [
    { id: 101, code:'D0001', name:'阿莫西林胶囊', dosage:'0.5g', frequency:'bid', route:'po', duration:7, quantity:14, price:12.5, note:'' },
    { id: 102, code:'D0101', name:'维生素C片', dosage:'0.1g', frequency:'qd', route:'po', duration:30, quantity:30, price:5.2, note:'日服' }
  ]
});

const templates = ref([]);
const showPreview = ref(false);

onMounted(()=>{
  // 初始化可以从 localStorage 或 seed 加载模板，这里用假数据
  templates.value = [ {name:'常用抗菌', items:[{code:'D0001',name:'阿莫西林胶囊',dosage:'0.5g',frequency:'bid',route:'po',duration:7,quantity:14,price:12.5}], note:'抗感染首选'} ];
});

const totalAmount = computed(()=> prescription.items.reduce((s,i)=>s + ((i.price||0)*(i.quantity||0)),0));

function onClearSearch(){ searchPatient.value=''; }
function openNewPrescription(){ Object.assign(patient,{name:'',gender:'M',age:0,visitNo:'',department:'',diagnosis:''}); prescription.items.splice(0); prescription.doctor='李医生'; prescription.note=''; prescription.date=new Date().toLocaleDateString(); }

function addDrugFromSearch(){ const q = drugSearch.value.trim().toLowerCase(); if(!q){ ElMessage.warning('请输入要添加的药品名称或编码'); return; }
  const found = DRUG_LIBRARY.find(d=>d.name.toLowerCase().includes(q) || d.code.toLowerCase()===q);
  const src = found || DRUG_LIBRARY[0];
  const nid = Math.max(100, ...prescription.items.map(i=>i.id), 100)+1;
  prescription.items.push({ id:nid, code:src.code, name:src.name, dosage:'', frequency:'qd', route:'po', duration:7, quantity:1, price:src.price, note:'' });
  drugSearch.value='';
}

function removeItem(id){ ElMessageBox.confirm('确认删除该条用药？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ const idx = prescription.items.findIndex(x=>x.id===id); if(idx>=0) prescription.items.splice(idx,1); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function duplicateItem(id){ const it = prescription.items.find(x=>x.id===id); if(!it) return; const nid = Math.max(100, ...prescription.items.map(i=>i.id), 100)+1; prescription.items.push(JSON.parse(JSON.stringify(Object.assign({},it,{id:nid})))); }

function validateAndSave(){ if(!patient.name){ ElMessage.warning('请填写患者姓名'); return; }
  if(prescription.items.length===0){ ElMessage.warning('处方为空，请添加至少一条药品'); return; }
  // 简单合法性校验：每条必须有数量和剂量
  for(const it of prescription.items){ if(!it.dosage){ ElMessage.warning(`请填写药品 ${it.name} 的剂量`); return; } if(!it.quantity || it.quantity<=0){ ElMessage.warning(`请填写药品 ${it.name} 的数量`); return; } }
  // 模拟保存
  ElMessage.success('处方已保存（模拟）');
}

function loadTemplate(){ if(templates.value.length===0){ ElMessage.info('没有可用模板'); return; }
  // 简单加载第一个模板
  const t = templates.value[0]; prescription.items.splice(0);
  t.items.forEach((it,idx)=>{
    const nid = Math.max(100, ...prescription.items.map(i=>i.id), 100)+1;
    prescription.items.push(Object.assign({id:nid,price: it.price||0,quantity:it.quantity||(it.duration||7)}, JSON.parse(JSON.stringify(it))));
  });
  ElMessage.success('已加载模板：'+t.name);
}

function saveTemplate(){ const name = prompt('请输入模板名称'); if(!name) return; templates.value.push({name, items: prescription.items.map(i=>({code:i.code,name:i.name,dosage:i.dosage,frequency:i.frequency,route:i.route,duration:i.duration,quantity:i.quantity,price:i.price,note:i.note})), note:prescription.note}); ElMessage.success('模板已保存'); }

function exportPrescription(){ const rows = [['编码','名称','剂量','频次','途径','疗程','数量','单价','备注']];
  prescription.items.forEach(it=> rows.push([it.code,it.name,it.dosage,it.frequency,it.route,it.duration,it.quantity,(it.price||0).toFixed(2),it.note||'']));
  const csv = rows.map(r=>r.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csv],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='prescription.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
  ElMessage.success('已导出处方');
}

function printPreview(){ showPreview.value = true; }
function doPrint(){ window.print(); }

function routeLabel(k){ if(k==='po') return '口服'; if(k==='iv') return '注射'; if(k==='topical') return '外用'; return k; }

</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
.card-title{font-weight:600;margin-bottom:8px}
</style>
